package nio.one;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/*
    文件复制
 */
public class ChannelTest03 {
    public static void main(String[] args) {
        File originFile = new File("E:\\mycode\\io\\src\\nio\\one\\test.txt");
        File targetFile = new File("E:\\mycode\\io\\src\\nio\\one\\test1.txt");
        try (
                FileInputStream fis = new FileInputStream(originFile);
                FileOutputStream fos = new FileOutputStream(targetFile);
                //获取通道
                FileChannel fisChannel = fis.getChannel();
                FileChannel fosChannel = fos.getChannel();
        ) {
            //创建缓冲区
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int flag = 0;
            while ((flag = fisChannel.read(buffer)) != -1) {   //读取数据到缓冲区
                //将缓冲区设置为读模式，将读到的数据写入到目标文件
                buffer.flip();
                fosChannel.write(buffer);
                //将缓冲区清空，准备下次写入数据
                buffer.clear();
            }
        } catch (Exception e) {
        }
    }
}
